package sv.ues.fia.adminperfildocentes;

import java.util.ArrayList;
import java.util.HashMap;

import sv.ues.fia.adminperfildocentes.adapter.ListFormacionDocenteAdapter;
import sv.ues.fia.adminperfildocentes.model.Formacion_Docente;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListarFormacionDocenteActivity extends Activity {
	
	ListFormacionDocenteAdapter mAdapter;
	ControlDB BDhelper;
	ListView lvFormacionDocente;
	EditText editbuscar;
	String id;
	ArrayList<HashMap<String, String>> array_sort = new ArrayList<HashMap<String, String>>();
	ArrayList<HashMap<String, String>> listarFormacionDocente = new ArrayList<HashMap<String, String>>();
	int textlength =0;
	
	//creamos el context menu
	final int CONTEXT_MENU_UPDATE =1;
	final int CONTEXT_MENU_ELIMINAR = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listar_formacion_docente);
		BDhelper = new ControlDB(this);
		
		Bundle bundle = getIntent().getExtras();
		id = bundle.getString("idDocente");
		BDhelper.abrir();
		listarFormacionDocente = BDhelper.listarFormacionDocente(id);
		BDhelper.cerrar();
		lvFormacionDocente = (ListView) findViewById(R.id.listviewformaciondoc);
		
		mAdapter = new ListFormacionDocenteAdapter(this,listarFormacionDocente);
		// Establecemos el adapter
		lvFormacionDocente.setAdapter(mAdapter);
			
		// registramos el menu
		registerForContextMenu(lvFormacionDocente);
		
		//filtrado con el edit
		editbuscar = (EditText) findViewById(R.id.editBusqueda);
		editbuscar.addTextChangedListener(new TextWatcher() {
			@Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        // When user changed the Text
				 textlength = editbuscar.getText().length();
	             array_sort.clear();
	                
	                for (int i = 0; i < listarFormacionDocente.size(); i++) {
	                	String itemTitulo = mAdapter.getItem(i);
	                	String itemIdFormacion = String.valueOf(mAdapter.getItemId(i));
	                	String itemInstitucion = mAdapter.getItemInstitucion(i);
	                	String itemAnio = mAdapter.getItemAnio(i);
	                	
	                	int longitud = itemTitulo.length();
	                    if (textlength <= longitud) {
	                        if (editbuscar.getText().toString().equalsIgnoreCase((String) itemTitulo.subSequence(0, textlength))) {
	                        	HashMap<String, String> actual = new HashMap<String, String>();
	                        	actual.put("TITULO", itemTitulo);
	                			actual.put("IDFORMACION", itemIdFormacion);
	                			actual.put("NOMBRE", itemInstitucion);
	                			actual.put("ANIO", itemAnio);
	                			
	                            array_sort.add(actual);
	                        }
	                    }
	                }
	                 
	                lvFormacionDocente.setAdapter(new  ListFormacionDocenteAdapter(ListarFormacionDocenteActivity.this, array_sort));
		    }
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) { }
		    @Override
		    public void afterTextChanged(Editable arg0) {}
		  });
	}

		
	public void llamarInsertarFormacion(View v)
	{
		Intent intent = new Intent(getApplicationContext(), InsertarFormacionDocenteActivity.class);
		intent.putExtra("idDocente", id);
		startActivity(intent);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) 
	{          
		menu.add(Menu.NONE, CONTEXT_MENU_UPDATE, Menu.NONE, R.string.modificar);
		menu.add(Menu.NONE, CONTEXT_MENU_ELIMINAR, Menu.NONE, R.string.eliminar);
		menu.setHeaderTitle(R.string.acciones);
		menu.setHeaderIcon(R.drawable.arrow);
	}
	
	//eventos para los item del context menu
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		int index = info.position;
		ListFormacionDocenteAdapter lstAdapter = (ListFormacionDocenteAdapter) lvFormacionDocente.getAdapter();
		long idExp= lstAdapter.getItemId(index);
		String idFormacionStr;
		idFormacionStr = String.valueOf(idExp);
		
		switch (item.getItemId()) 
		{
			
			case CONTEXT_MENU_UPDATE:
				Intent intentActualizar = new Intent(this, ActualizarFormacionDocenteActivity.class);
				intentActualizar.putExtra("idFormacion", idFormacionStr);
				intentActualizar.putExtra("idDocente", id);
				startActivity(intentActualizar);  
			       
				return(true);    
			case CONTEXT_MENU_ELIMINAR:
				eliminarFormacionDocente(idFormacionStr,id);
 			       
				return(true);   
		
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void eliminarFormacionDocente(final String idFormacion,final String iddocente)
	{
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				this);
 
			// set title
			alertDialogBuilder.setTitle(R.string.eliminareg);
 
			// set dialog message
			alertDialogBuilder
				.setMessage(R.string.msjeliminar)
				.setCancelable(false)
				.setPositiveButton(R.string.si,new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int idOption) {
						
						Formacion_Docente formacionDocente = new Formacion_Docente();

						BDhelper.abrir();
						formacionDocente = BDhelper.consultarFormacionDocente(id, idFormacion);
						int accion = BDhelper.eliminarFormacionDocente(formacionDocente);
						BDhelper.cerrar();
						if (accion == -1 || accion == 0) {
							Toast.makeText(getBaseContext(), R.string.erroreliminar, Toast.LENGTH_SHORT).show();
							Intent intent1 = new Intent(getApplicationContext(), DocenteMenuActivity.class);
							intent1.putExtra("idDocente", Long.valueOf(formacionDocente.getIddocente()));
							startActivity(intent1);
						} else {
							Toast.makeText(getBaseContext(), R.string.okeliminar, Toast.LENGTH_SHORT).show();
							Intent intent2 = new Intent(getApplicationContext(), DocenteMenuActivity.class);
							intent2.putExtra("idDocente", Long.valueOf(formacionDocente.getIddocente()));
							startActivity(intent2);
						}
					
						
					}
				  })
				.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, just close
						// the dialog box and do nothing
						dialog.cancel();
					}
				});
 
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();
	}

}
